import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { FetchService } from '../../../core/net/fetch.service';
import { UtilService } from '../../../core/util/util.service';
import * as _ from 'lodash';
import { NzMessageService, NzModalService, UploadChangeParam, UploadFile } from 'ng-zorro-antd';

const HrHash = {
    龙羊峡水库: 'lyx_early_8',
    刘家峡水库: 'ljx_early_8',
    下河沿断面: 'xhydm_early_8',
    石嘴山断面: 'szs_early_8',
    青铜峡坝下: 'qtx_early_8'
};
const HrLastHash = {
    下河沿断面: 'xhydm_last_avg',
    石嘴山断面: 'szs_last_avg',
    青铜峡坝下: 'qtx_last_avg'
};
const WebHrHash = {
    lyx_early_8: {
        label: '龙羊峡水库',
        props: 'flow'
    },
    ljx_early_8: {
        label: '刘家峡水库',
        props: 'flow'
    },
    xhydm_early_8: {
        label: '下河沿断面',
        props: 'flow'
    },
    xhydm_last_avg: {
        label: '下河沿断面',
        props: 'flowLast'
    },
    qtx_early_8: {
        label: '青铜峡坝下',
        props: 'flow'
    },
    qtx_last_avg: {
        label: '青铜峡坝下',
        props: 'flowLast'
    },
    szs_early_8: {
        label: '石嘴山断面',
        props: 'flow'
    },
    szs_last_avg: {
        label: '石嘴山断面',
        props: 'flowLast'
    }
};

@Component({
    selector: 'app-data-publish',
    templateUrl: './data-publish.component.html',
    styleUrls: ['./data-publish.component.scss']
})
export class DataPublishComponent implements OnInit {
    publishType = 2; //  发布类型： 0短信 1网页
    resCache: any;
    yellowRiverForm: FormGroup;
    canalImportForm: FormGroup;
    listOfCanalFormControl: Array<{
        controlInstance: string;
        label: string;
    }> = [];
    irrigateForm: FormGroup;
    lakeForm: FormGroup;
    listOfLakeFormControl: Array<{ controlInstance: string; label: string }> = [];
    modalShow: boolean = false;
    isPublishLoading = false;
    lyxChecked = true;
    ljxChecked = true;
    xhyChecked = true;
    qtxChecked = true;
    szsChecked = true;
    smsTpl = '';
    canalTplArr = [];
    lakeTplArr = [];
    @ViewChild('smsHTML', {static: false}) smsHTML: ElementRef;

    today = new Date();
    webResCache: any;
    yellowRiverWebForm: FormGroup;
    editWebWrCache: { [key: string]: { edit: boolean; data: any } } = {};
    editWebBusCache: { [key: string]: { edit: boolean; data: any } } = {};
    webWrTableData = {};
    webWrTitleKeys = [];

    webBusTableDatas = [];
    webIrrForm: FormGroup;

    uploadUrl = `${(window as any).environment.apiBaseUrl}comm/file/upload`;
    uploadFileId = '';
    showUploadList = {
        showPreviewIcon: true,
        showRemoveIcon: true,
        hidePreviewIconInNonImage: true
    };
    fileList = [];
    previewImage: string | undefined = '';
    previewVisible = false;
    handlePreview = (file: UploadFile) => {
        this.previewImage = file.url || file.thumbUrl;
        this.previewVisible = true;
    }

    constructor(
        private fb: FormBuilder,
        private fetchService: FetchService,
        private message: NzMessageService,
        private modalService: NzModalService,
        private util: UtilService
    ) {
    }

    ngOnInit() {
        this.yellowRiverForm = new FormGroup({
            lyx_early_8: new FormControl(null),
            ljx_early_8: new FormControl(null),
            xhydm_early_8: new FormControl(null),
            xhydm_last_avg: new FormControl(null),
            qtx_early_8: new FormControl(null),
            qtx_last_avg: new FormControl(null),
            szs_early_8: new FormControl(null),
            szs_last_avg: new FormControl(null)
        });
        this.yellowRiverWebForm = new FormGroup({
            lyx_early_8: new FormControl(null),
            ljx_early_8: new FormControl(null),
            xhydm_early_8: new FormControl(null),
            xhydm_last_avg: new FormControl(null),
            qtx_early_8: new FormControl(null),
            qtx_last_avg: new FormControl(null),
            szs_early_8: new FormControl(null),
            szs_last_avg: new FormControl(null)
        });
        this.webIrrForm = this.fb.group({
            mwoTotal: [null]
        });
        // this.yellowRiverForm.disable();
        this.irrigateForm = this.fb.group({
            id: [null],
            sideId: [null],
            sideName: [''],
            time: [null],
            planArea: [null],
            actArea: [null],
            areaPer: [null]
        });

        this.canalImportForm = this.fb.group({
            total: [null]
        });

        this.lakeForm = this.fb.group({
            total: [null],
            percentage: [null]
        });

        this.getData();
    }

    getData(): void {
        if (this.publishType === 0) {
            this.fetchService.post('sms/publish/list', {}).subscribe(res => {
                if (res) {
                    this.resCache = res;
                    this.setHrData(res['wrsSmsHrSideDatas']);
                    this.getIrrData(res['wrsSmsIrrSideDatas']);
                    this.getLakeData(res['wrsSmsLwSideDatas']);
                    this.getCanalData(res['wrsSmsWfSideDatas']);
                }
            });
        } else if (this.publishType === 1) {
            this.fetchService.post('web/publish/list', {}).subscribe(res => {
                if (res) {
                    this.webResCache = res;
                    this.getWebWrData(res['wrsPublishWrsDatas']);
                    this.getWebBusData(res['wrsPublishBusDatas']);
                    this.getWebAppPlatformData(res);
                }
            });
        }
    }

    /****** 网页发布 *********/
    getWebWrData(list) {
        const group = _.groupBy(list, 'sideParentName');
        this.webWrTitleKeys = Object.keys(group);
        this.webWrTableData = group;
        this.updateWebWrEditCache();
    }

    updateWebWrEditCache(): void {
        const listOfData = _.flatten(Object.values(this.webWrTableData));
        listOfData.forEach((item: any) => {
            this.editWebWrCache[item.sideId] = {
                edit: false,
                data: {...item}
            };
        });
    }

    startWebWrEdit(id): void {
        this.editWebWrCache[id].edit = true;
    }

    saveWebWrEdit(id: string): void {
        const listOfData = _.flatten(Object.values(this.webWrTableData));
        const index = listOfData.findIndex((item: any) => item.sideId === id);
        Object.assign(listOfData[index], this.editWebWrCache[id].data);
        this.editWebWrCache[id].edit = false;
        this.webWrTableData = _.groupBy(listOfData, 'sideParentName');
    }

    cancelWebWrEdit(id): void {
        this.modalService.confirm({
            nzTitle: '确认取消',
            nzContent: '确认取消修改？',
            nzOnOk: () => {
                const listOfData = _.flatten(Object.values(this.webWrTableData));
                const index = listOfData.findIndex((item: any) => item.sideId === id);
                this.editWebWrCache[id] = {
                    data: {...listOfData[index]},
                    edit: false
                };
            }
        });
    }

    getWebBusData(list) {
        const thirdLen = Math.ceil(list.length / 3);
        const firstData = _.slice(list, 0, thirdLen);
        const secondData = _.slice(list, thirdLen, 2 * thirdLen);
        const thirdData = _.slice(list, 2 * thirdLen);
        this.webBusTableDatas = [firstData, secondData, thirdData];
        this.updateWebBusEditCache();
    }

    updateWebBusEditCache(): void {
        const listOfData = _.flatten(this.webBusTableDatas);
        listOfData.forEach(item => {
            this.editWebBusCache[item.sideId] = {
                edit: false,
                data: {...item}
            };
        });
    }

    startWebBusEdit(id): void {
        this.editWebBusCache[id].edit = true;
    }

    saveWebBusEdit(id: string): void {
        const listOfData = _.flatten(this.webBusTableDatas);
        const index = listOfData.findIndex(item => item.sideId === id);
        Object.assign(listOfData[index], this.editWebBusCache[id].data);
        this.editWebBusCache[id].edit = false;
        const thirdLen = Math.ceil(listOfData.length / 3);
        const firstData = _.slice(listOfData, 0, thirdLen);
        const secondData = _.slice(listOfData, thirdLen, 2 * thirdLen);
        const thirdData = _.slice(listOfData, 2 * thirdLen);
        this.webBusTableDatas = [firstData, secondData, thirdData];
    }

    cancelWebBusEdit(id): void {
        const listOfData = _.flatten(this.webBusTableDatas);
        const index = listOfData.findIndex(item => item.sideId === id);
        this.editWebBusCache[id] = {
            data: {...listOfData[index]},
            edit: false
        };
    }

    getWebAppPlatformData(res) {
        this.getWebHrData(res['wrsSmsHrSideDatas']);
        this.getWebIrrData(res['wrsMuwIrrData']);
        this.getWebImgFile(res);
    }

    //  实时水情
    getWebIrrData(list) {
        this.webIrrForm.patchValue(list);
    }

    getWebIrrFormValue(): any {
        const val = this.webIrrForm.value;
        const irrVal = _.cloneDeep(this.webResCache['wrsMuwIrrData']);
        _.assign(irrVal, val);
        return {wrsMuwIrrData: irrVal};
    }

    //  黄鹤水情
    getWebHrData(list) {
        const obj = {};
        list.forEach(item => {
            obj[HrHash[item['sideName']]] = item['flow'];
            if (HrLastHash[item['sideName']]) {
                obj[HrLastHash[item['sideName']]] = item['flowLast'];
            }
        });
        this.yellowRiverWebForm.patchValue(obj);
    }

    getWebHrFormValue(): any {
        const val = this.yellowRiverWebForm.value;
        const hrList = _.cloneDeep(this.webResCache['wrsSmsHrSideDatas']);
        const keyArr = Object.keys(val);
        keyArr.forEach(key => {
            hrList.forEach(item => {
                if (item['sideName'] === WebHrHash[key].label) {
                    item[WebHrHash[key].props] = val[key];
                }
            });
        });
        return {wrsSmsHrSideDatas: hrList};
    }

    //  图片
    getWebImgFile(data): any {
        this.uploadFileId = data['wrsSmsHrSidePic'].fileId;
        const imgSrc = `${(window as any).environment.apiBaseUrl}comm/file/view/${
            this.uploadFileId
            }`;
        if (this.uploadFileId) {
            this.fileList = [
                {
                    name: '',
                    status: 'done',
                    url: imgSrc,
                    thumbUrl: imgSrc
                }
            ];
        }
    }

    handleChange({file, fileList}: UploadChangeParam): void {
        const status = file.status;
        this.uploadFileId = '';
        if (status !== 'uploading') {
            // console.log(file, fileList);
        }
        if (status === 'done') {
            this.uploadFileId = file.response.data.id;
        } else if (status === 'error') {
            this.message.error('上传失败，请重新选择图片');
        }
    }

    /****** 短信发布 *********/
    setHrData(list): void {
        const obj = {};
        list.forEach(item => {
            obj[HrHash[item['sideName']]] = item['flow'];
            if (HrLastHash[item['sideName']]) {
                obj[HrLastHash[item['sideName']]] = item['flowLast'];
            }
        });
        this.yellowRiverForm.patchValue(obj);
    }

    getCanalData(list): void {
        const canalTotal = this.util.sum(
            this.util.getItemValues(list, 'flow', true)
        );
        const value = {total: canalTotal};
        this.canalTplArr = [];
        this.listOfCanalFormControl = list.map(item => {
            const key = `fc${item['sideId']}`;
            value[key] = item['flow'];
            this.canalTplArr.push(
                `${item['sideName']} ${this.getSmsVal(item['flow'])}m³/s`
            );
            return {
                label: item['sideName'],
                controlInstance: key
            };
        });
        this.listOfCanalFormControl.forEach(item => {
            this.canalImportForm.addControl(
                item.controlInstance,
                new FormControl(null)
            );
        });
        this.canalImportForm.patchValue(value);
    }

    getIrrData(list): void {
        if (list.length) {
            const data = _.cloneDeep(list[0]);
            data['areaPer'] = data['areaPer'] * 100;
            this.irrigateForm.patchValue(data);
        }
    }

    getLakeData(list): void {
        const totalObj = _.find(list, item => {
            return item['sideId'] === 1;
        });
        const value = {
            total: totalObj['actVal'],
            percentage: totalObj['valPer'] ? totalObj['valPer'] * 100 : totalObj['valPer']
        };
        const newList = _.drop(list);
        this.lakeTplArr = [];
        this.listOfLakeFormControl = newList.map(item => {
            const key = `fc${item['sideId']}`;
            value[key] = item['actVal'];
            this.lakeTplArr.push(
                `${item['sideName']} ${this.getSmsVal(item['actVal'])}万m³`
            );
            return {
                label: item['sideName'],
                controlInstance: key
            };
        });
        this.listOfLakeFormControl.forEach(item => {
            this.lakeForm.addControl(item.controlInstance, new FormControl(null));
        });
        this.lakeForm.patchValue(value);
    }

    preview(): void {
        this.modalShow = true;
        this.getData();
        const canalTpl = _.join(this.canalTplArr, '，');
        const lakeTpl = _.join(this.lakeTplArr, '，');
        const lyxTpl = this.lyxChecked ? ` <span>
            龙羊峡水库 早8时入库 ${this.getSmsVal(
            this.yellowRiverForm.value.lyx_early_8
        )}m³/s；</span>` : '';
        const ljxTpl = this.ljxChecked ? `<span>
             刘家峡水库 早8时出库${this.getSmsVal(
            this.yellowRiverForm.value.ljx_early_8
        )}m³/s；</span>` : '';
        const xhyTpl = this.xhyChecked ? `<span>
             下河沿断面 早8时流量 ${this.getSmsVal(
            this.yellowRiverForm.value.xhydm_early_8
        )}m³/s，昨日均 ${this.getSmsVal(
            this.yellowRiverForm.value.xhydm_last_avg
        )}m³/s；</span>` : '';
        const qtxTpl = this.qtxChecked ? `<span>
              青铜峡坝下 早8时流量 ${this.getSmsVal(
            this.yellowRiverForm.value.qtx_early_8
        )}m³/s，昨日均 ${this.getSmsVal(
            this.yellowRiverForm.value.qtx_last_avg
        )}m³/s；</span>` : '';
        const szsTpl = this.szsChecked ? `<span>
              石嘴山断面 早8时流量 ${this.getSmsVal(
            this.yellowRiverForm.value.szs_early_8
        )}m³/s，昨日均 ${this.getSmsVal(
            this.yellowRiverForm.value.szs_last_avg
        )}m³/s；</span>` : '';
        this.smsTpl = `
        <h3>一、黄河水情</h3>
            <p>
            ${lyxTpl}
            ${ljxTpl}
            ${xhyTpl}
            ${qtxTpl}
            ${szsTpl}
          </p>
        <h3>二、干渠引水</h3>
            <p>今日各干渠引水流量合计 ${this.getSmsVal(
            this.canalImportForm.value.total
        )}m³/s；<p>
            <p>${canalTpl}。</p>
        <h3>三、灌溉进度</h3>
            <p>冬灌（夏秋灌）应灌 ${this.getSmsVal(
            this.irrigateForm.value.planArea
        )}万亩，已灌 ${this.getSmsVal(
            this.irrigateForm.value.actArea
        )}万亩，占比 ${this.getSmsVal(this.irrigateForm.value.areaPer)}%。</p>
        <h3>四、湖泊生态湿地补水</h3>
           <p>冬灌（夏秋灌）累计补水量 ${this.getSmsVal(
            this.lakeForm.value.total
        )}万m³，其中，<p>
            <p>${lakeTpl}。</p>
        `;
    }

    smsPublish(): void {
        this.isPublishLoading = true;
        console.log(this.smsHTML.nativeElement.innerText);
        const content = this.smsHTML.nativeElement.innerText;
        this.fetchService
            .post('sms/publish/sendMsg', {
                content: content
            })
            .subscribe(res => {
                this.modalShow = false;
                this.isPublishLoading = false;
                this.message.success('发送成功');
            });
    }

    onCancel() {
        this.modalShow = false;
    }

    confirm(type): void {
        if (this.publishType === 0) {
            let params = {};
            switch (type) {
                case 1:
                    params = this.getCanalFormValue();
                    break;
                case 2:
                    params = this.getIrrFormValue();
                    break;
                case 3:
                    params = this.getLakeFormValue();
                    break;
            }
            this.fetchService.post('sms/publish/add', params).subscribe(res => {
                this.message.success('提交成功');
                this.reset(type);
            });
        } else {
            let params = {};
            switch (type) {
                case 1:
                    params = {
                        wrsPublishWrsDatas: _.flatten(Object.values(this.webWrTableData))
                    };
                    break;
                case 2:
                    params = {
                        wrsPublishBusDatas: _.flatten(this.webBusTableDatas)
                    };
                    break;
                case 3:
                    params = _.assign(
                        {},
                        this.getWebIrrFormValue(),
                        this.getWebHrFormValue(),
                        {
                            wrsSmsHrSidePic: _.assign(
                                _.cloneDeep(this.webResCache['wrsSmsHrSidePic']),
                                {fileId: this.uploadFileId}
                            )
                        }
                    );
                    break;
            }
            console.log(params);
            this.fetchService.post('web/publish/add', params).subscribe(res => {
                this.message.success('提交成功');
                this.reset(type);
            });
        }
    }

    getCanalFormValue(): any {
        const val = this.canalImportForm.value;
        const canalList = _.cloneDeep(this.resCache['wrsSmsWfSideDatas']);
        const keyArr = Object.keys(val);
        keyArr.forEach(key => {
            //  key以fc开头
            if (key.slice(0, 2) === 'fc' && key !== 'total') {
                canalList.forEach(item => {
                    if (item['sideId'] === parseInt(_.trim(key, 'fc'), 10)) {
                        item['flow'] = val[key];
                    }
                });
            }
        });
        return {wrsSmsWfSideDatas: canalList};
    }

    getIrrFormValue(): any {
        const params = [];
        params.push(this.irrigateForm.value);
        params[0]['areaPer'] = params[0]['areaPer'] ? params[0]['areaPer'] / 100 : params[0]['areaPer'];
        // const irrList = _.cloneDeep(this.resCache["wrsSmsIrrSideDatas"]);
        // _.assign(irrList[0], val);
        return {wrsSmsIrrSideDatas: params};
    }

    getLakeFormValue(): any {
        const val = this.lakeForm.value;
        val['percentage'] = val['percentage'] ? val['percentage'] / 100 : val['percentage'];
        const lakeList = _.cloneDeep(this.resCache['wrsSmsLwSideDatas']);
        const keyArr = Object.keys(val);
        keyArr.forEach(key => {
            //  key以fc开头
            if (key.slice(0, 2) === 'fc' && key !== 'total' && key !== 'percentage') {
                lakeList.forEach(item => {
                    if (item['sideId'] === parseInt(_.trim(key, 'fc'), 10)) {
                        item['actVal'] = val[key];
                    }
                });
            }
        });
        return {wrsSmsLwSideDatas: lakeList};
    }

    reset(type): void {
        if (this.publishType === 0) {
            this.fetchService.post('sms/publish/list', {}).subscribe(res => {
                if (res) {
                    switch (type) {
                        case 1:
                            this.getCanalData(res['wrsSmsWfSideDatas']);
                            break;
                        case 2:
                            this.getIrrData(res['wrsSmsIrrSideDatas']);
                            break;
                        case 3:
                            this.getLakeData(res['wrsSmsLwSideDatas']);
                            break;
                    }
                }
            });
        } else {
            this.fetchService.post('web/publish/list', {}).subscribe(res => {
                if (res) {
                    switch (type) {
                        case 1:
                            this.getWebWrData(res['wrsPublishWrsDatas']);
                            break;
                        case 2:
                            this.getWebBusData(res['wrsPublishBusDatas']);
                            break;
                        case 3:
                            this.getWebAppPlatformData(res);
                            break;
                    }
                }
            });
        }
    }

    private getSmsVal(val): string {
        const data = JSON.stringify(val);
        if (data === 'undefined' || data === 'null' || data === '') {
            return '-';
        } else {
            return val;
        }
    }
}
